package com.zhangye.test.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * Created by cuigx on 2015/6/4.
 */
public class HttpUtil {

//    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    
	
	
	
//    public static HttpResponse httpDelete(String url,Map<String,String> headers,String encode){    
//        HttpResponse response;  
//        if(encode == null){    
//            encode = "utf-8";    
//        }    
//        String content = null;    
//        //since 4.3 不再使用 DefaultHttpClient    
//        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();     
//        HttpDelete httpdelete = new HttpDelete(url);    
//        //设置header  
//        if (headers != null && headers.size() > 0) {  
//            for (Map.Entry<String, String> entry : headers.entrySet()) {  
//                httpdelete.setHeader(entry.getKey(),entry.getValue());  
//            }  
//        }  
//        CloseableHttpResponse httpResponse = null;    
//        try {    
//            httpResponse = closeableHttpClient.execute(httpdelete);    
//            HttpEntity entity = httpResponse.getEntity();    
//            content = EntityUtils.toString(entity, encode);    
//            response.setBody(content);  
//            response.setHeaders(httpResponse.getAllHeaders());  
//            response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());  
//            response.setStatusCode(httpResponse.getStatusLine().getStatusCode());  
//        } catch (Exception e) {    
//            e.printStackTrace();    
//        }finally{    
//            try {    
//                httpResponse.close();    
//            } catch (IOException e) {    
//                e.printStackTrace();    
//            }    
//        }    
//        try {   //关闭连接、释放资源    
//            closeableHttpClient.close();    
//        } catch (IOException e) {    
//            e.printStackTrace();    
//        }      
//        return response;    
//    }    
      
	
    public static String requestPost(String requestUrl, String content) {
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(requestUrl);
//            logger.info("http post request :" + requestUrl);
            if (!StringUtils.isEmpty(content)) {
                httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
                httpPost.setEntity(new StringEntity(content, "UTF-8"));
//                logger.info("http post content :" + content);
            }

            HttpResponse resp = httpclient.execute(httpPost);
            if (resp.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("API响应异常：" + resp.getStatusLine().getStatusCode());
            }
            HttpEntity entity = resp.getEntity();
            //解析响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
//            logger.info("http post response :" + sb.toString());
            return sb.toString();
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
//            logger.error(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    public static String requestPut(String requestUrl, String content) {
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPut httpPut = new HttpPut(requestUrl);
//            logger.info("http put request :" + requestUrl);
            if (!StringUtils.isEmpty(content)) {
            	httpPut.addHeader("Content-Type", "application/json; charset=UTF-8");
            	httpPut.setEntity(new StringEntity(content, "UTF-8"));
            }

            HttpResponse resp = httpclient.execute(httpPut);
            if (resp.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("API响应异常：" + resp.getStatusLine().getStatusCode());
            }
            HttpEntity entity = resp.getEntity();
            //解析响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
            return sb.toString();
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
//            logger.error(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    public static String requestGet(String requestUrl) {
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(requestUrl);
//            logger.info("http get request :" + requestUrl);
            HttpResponse resp = httpclient.execute(httpGet);
            if (resp.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("响应异常：" + resp.getStatusLine().getStatusCode());
            }
            HttpEntity entity = resp.getEntity();
            //解析响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "utf-8"));
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
//            logger.info("http get response :" + sb.toString());
            return sb.toString();
        } catch (Exception e) {
//            logger.error(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    public static String request(String requestUrl, String requestMethod,
                                 String requestStr) {
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            //GET/POST
            conn.setRequestMethod(requestMethod);

//            logger.info("http request :" + requestUrl + " " + requestMethod);
            if (null != requestStr && "POST".equalsIgnoreCase(requestMethod)) {
//                logger.info("request post content : " + requestStr);
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(requestStr.getBytes("UTF-8"));
                outputStream.close();
            }

            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
//            logger.info("http response :" + buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
    
    
    public static String getShortUrl(String longUrl){

        String random = getsinakey();
		String url = String.format("http://api.weibo.com/2/short_url/shorten.json?source=%s&url_long=%s", random,longUrl);
		String content = "";
		try{
	        content = HttpUtil.requestGet(url);
		}catch(Exception e){
			e.printStackTrace();
		}
        if(content != null && !"".equals(content)){
        	JSONObject json = JSONObject.parseObject(content);
        	JSONArray jsonArray = json.getJSONArray("urls");//查询结果
        	String sUrl = jsonArray.getString(0);
        	net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(sUrl);  
            String shortUrl = jsonObject.getString("url_short");
            return shortUrl;
        }
        return null;
    }
    private static String getsinakey(){
        String[] shortUrl= new String[]{"5786724301", "2849184197", "1206405345", "202088835", "211160679"};
        int index = (int) (Math.random() * shortUrl.length);
        return shortUrl[index];
	}
}
